package com.common.util;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

/**
 * 创建日期 2016/12/9
 * IP工具
 */
public class IpUtil {

    /**
     * 获取本机的IP以及本地计算机名
     *
     * @return
     */
    public static String getLocalIp() {
        String localname = "";
        String localip = "";
        try {
            InetAddress.getLocalHost();
            localname = InetAddress.getLocalHost().getHostName();
            localip = InetAddress.getLocalHost().getHostAddress();
        } catch (Exception e) {
        }
        return localname + ":" + localip;
    }

    /**
     * 获取request请求的IP
     * @param request
     * @return
     */
    public static String getRemoteIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if (forwarded != null) {
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        return ip;
    }

}
